﻿using SmartCustomerService.Web.Services;
using System.Diagnostics;

var builder = WebApplication.CreateBuilder(args);

// 完全禁用调试功能
builder.WebHost.UseUrls("http://localhost:5000", "https://localhost:5001");
builder.WebHost.ConfigureKestrel(options =>
{
    options.Limits.MaxRequestBodySize = 10 * 1024 * 1024; // 10MB
});

// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();

// 配置 Swagger
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
    {
        Title = "智能客服系统 API",
        Version = "v1",
        Description = "基于阿里云百炼模型的智能客服系统 API 文档",
        Contact = new Microsoft.OpenApi.Models.OpenApiContact
        {
            Name = "智能客服系统",
            Email = "support@example.com"
        }
    });
    
    // 包含 XML 注释（如果有的话）
    var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = System.IO.Path.Combine(System.AppContext.BaseDirectory, xmlFile);
    if (System.IO.File.Exists(xmlPath))
    {
        c.IncludeXmlComments(xmlPath);
    }
});

// 注册阿里云百炼模型服务
builder.Services.AddScoped<IAliyunBailianCustomerService, AliyunBailianCustomerService>();
builder.Services.AddHttpClient<IAliyunBailianClient, AliyunBailianClient>()
	.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
	{
		AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.Brotli
	});
// 轻量RAG服务
builder.Services.AddSingleton<ISimpleRetrievalService, SimpleRetrievalService>();

//配置CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader();
    });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
// 始终启用Swagger，不限制环境
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "智能客服系统 API v1");
    c.RoutePrefix = "swagger"; // 设置 Swagger UI 的路由前缀
    c.DocumentTitle = "智能客服系统 API 文档";
    c.DefaultModelsExpandDepth(-1); // 默认展开模型
    c.DisplayRequestDuration(); // 显示请求持续时间
});

// 开发环境下关闭强制HTTPS跳转，避免本地代理到http端口被重定向导致超时
if (!app.Environment.IsDevelopment())
{
    app.UseHttpsRedirection();
}

// 添加静态文件支持
app.UseStaticFiles();
app.UseDefaultFiles();

app.UseCors("AllowAll");

app.UseAuthorization();

app.MapControllers();

// 添加根路径重定向到 Swagger
app.MapGet("/", () => Results.Redirect("/swagger"));

// 添加 API 信息端点
app.MapGet("/api/info", () => new
{
    message = "智能客服系统API",
    status = "运行中",
    timestamp = DateTime.Now,
    version = "v1",
    models = new[]
    {
        "阿里云百炼 (云端API)"
    },
    endpoints = new[]
    {
        "/api/AliyunBailian/chat - 阿里云百炼客服",
        "/api/AliyunBailian/chat/stream - 流式客服对话",
        "/api/AliyunBailian/history - 获取聊天历史",
        "/api/AliyunBailian/health - 阿里云服务健康检查",
        "/api/ping - 连通性测试",
        "/swagger - API文档"
    }
});

// 轻量连通性探测
app.MapGet("/api/ping", () => Results.Ok(new { success = true, time = DateTime.Now }));

//// 简化启动信息，不自动打开浏览器
//app.Lifetime.ApplicationStarted.Register(() =>
//{
//    Console.WriteLine();
//    Console.WriteLine(" 智能客服系统已启动！");
//    Console.WriteLine($" Swagger API 文档: https://localhost:5001/swagger");
//    Console.WriteLine($" HTTP 版本: http://localhost:5000/swagger");
//    Console.WriteLine();
//    Console.WriteLine("支持AI模型:");
//    Console.WriteLine("  - 阿里云百炼 (云端API)");
//    Console.WriteLine();
//    Console.WriteLine("请手动在浏览器中访问上述地址");
//    Console.WriteLine("按 Ctrl+C 停止应用");
//});

app.Run();
